﻿DECLARE @Var_PatientId   VARCHAR(100)
DECLARE @Var_DataSource  VARCHAR(100)
DECLARE @Var_Flag        VARCHAR(100)
DECLARE @Var_ApplyNum    VARCHAR(100)

DECLARE @HIS_ApplyNumStr VARCHAR(256)
DECLARE @HIS_IsPrintStr  VARCHAR(256)

SET @Var_DataSource = '''' + @DataSource_In + ''''
SET @Var_PatientId = '''' + @PatientId_In + ''''
SET @Var_ApplyNum = '''' + @ApplyNum_In + ''''
SET @Var_Flag = @Flag_In

IF @Var_ApplyNum IS NOT NULL
BEGIN
   SET @HIS_ApplyNumStr = 'AND a.Applynum = ' + @Var_ApplyNum
END
ELSE
BEGIN
	SET @HIS_ApplyNumStr = ''
END

IF @Var_Flag = 0
BEGIN
 SET @HIS_IsPrintStr = 'AND a.PrnFlag = NULL'
END
ELSE IF @Var_Flag = 1
BEGIN
 SET @HIS_IsPrintStr = 'AND a.PrnFlag = 1'
END
ELSE IF @Var_Flag = 2
BEGIN
 SET @HIS_IsPrintStr = ''
END

DECLARE @sqltext NVARCHAR(MAX)
SET @sqltext=N'
SELECT a.PatientName
      ,a.Applynum AS ApplyNum
      ,a.ApplicationName as Name
      ,ModalityType AS Type
      ,case when a.MZNum is not null then ''门诊申请单'' else ''住院申请单'' end as ApplicationFrom
      ,case when a.JZDate is null then 0 else case when a.YJCheckDate is not null then 2 else 1 end end as State
      ,a.MZNum 
      ,a.ZYNum  
      ,a.BedNo as BedNum
      ,a.YLDYName as YLDY
      ,isnull(a.LYKSCODE,a.yskscode) AS ApplyDeptCode
      ,isnull(a.LYKSNAME,a.ysksname) AS ApplyDeptName
      ,a.yscode AS ApplyDoctCode
      ,a.ysname AS Applydoctname
      ,a.applydate 
      ,a.FSKSCODE as ExecDeptCode
      ,a.fsksname as ExecDeptName
      ,a.yjcheckdate as ExecDate
      ,b.BodyPartExamined as BodyPart
      ,b.RoomName as ScanRoom
      ,b.ScanWay
      ,b.ReportText1 as Description
      ,b.ReportText2 as Conclusion
      ,a.Note
      ,b.DiagnosesText as Diagnose
      ,b.ReportDoctor as ReportDoctName
      ,b.ReportDate
  FROM patient_applicationsheet a(nolock),OPENDATASOURCE(''SQLOLEDB'',' +@Var_DataSource  + ').DICOMSERVER.dbo.PatientSchedule b
 WHERE a.ApplyNum=b.ApplyFromHis and
       a.PatientId=' + @Var_PatientId + ' and a.Deldate is null and b.reportdate is not null ' + @HIS_IsPrintStr + @HIS_ApplyNumStr
EXEC sp_executesql @sqltext